package com.mxsoft.takeaway.web.error;

import com.mxsoft.takeaway.util.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;

import java.util.List;

/**
 * Controller统一异常处理
 * Controller advice to translate the server side exceptions to client-friendly json structures.
 */
@Slf4j
@ControllerAdvice
public class ExceptionTranslator {

//    private Gson gson = new Gson();

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public HttpResult processRuntimeException(Exception ex) throws Exception {
        log.error("Exception logged by ExceptionTranslator:", ex);
        if (ex instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException e = (MethodArgumentNotValidException) ex;
            BindingResult bindingResult = e.getBindingResult();
            logReqParameter(e);
            List<ObjectError> fieldError = bindingResult.getAllErrors();
            StringBuilder message = new StringBuilder();
            for (ObjectError objectError : fieldError) {
                message.append(objectError.getDefaultMessage() + ";");
            }
            return HttpResult.builder().failed(message.toString()).build();
        } else if (ex instanceof MaxUploadSizeExceededException) {
            return HttpResult.builder().failed("上传文件的大小不能超过10M").build();
        } else if (ex instanceof MultipartException) {
            return HttpResult.builder().failed("上传文件的大小不能超过10M").build();
        } else {
            return HttpResult.builder().failed().build();
        }
    }

    private void logReqParameter(MethodArgumentNotValidException e) {
        try {
//            UserDto user = SubjectUtils.getUser();
//            StaffDto staff = SubjectUtils.getStaff();
//            BindingResult bindingResult = e.getBindingResult();
//            //日志记录入参数
//            StringBuilder builder = new StringBuilder();
//            builder.append("User: ");
//            builder.append(gson.toJson(user));
//            builder.append(" Staff: ");
//            builder.append(gson.toJson(staff));
//            builder.append(" Method: ");
//            builder.append(e.getParameter().getMethod().toString());
//            builder.append(" -> ");
//            builder.append(gson.toJson(bindingResult.getTarget()));
//            log.error(builder.toString());
        } catch (Exception ex) {
            log.error("记录校验异常日志： ", ex);
        }
    }
}
